﻿<?php
class InstallAction extends Action{
    
    /**
     * 安装程序
     * */
	public function index(){
        $project_cn = $_REQUEST['project_cn'];
        $project_en = $_REQUEST['project_en'];
        $db_addr = $_REQUEST['db_addr'];
        $db_user = $_REQUEST['db_user'];
        $db_pwd = $_REQUEST['db_pwd'];
        if(!isset($project_cn) || !isset($project_en) || !isset($db_addr)
            || !isset($db_user) || !isset($db_pwd)){
            echo '请补全未填写的必须字段。';
            exit(0);
        }
        $abs_dir=dirname(dirname(dirname(dirname(__FILE__))));
        $this->initDB($abs_dir.'/Admin/Conf' , $project_cn , $project_en , $db_addr , $db_user , $db_pwd);
        $this->copyFile($abs_dir.'/Admin/Conf' , $project_en , $db_addr , $db_user , $db_pwd);
        $this->deleteFile($abs_dir.'/Admin/Runtime');
        echo '项目成功安装，<a href="/'.$project_en.'">点击进入</a>。';
	}
    
    protected function initDB($sql_path ,$project_cn ,$project_en , $db_addr , $db_user , $db_pwd){
        $conn = mysql_connect($db_addr,$db_user,$db_pwd);
        mysql_query("set names utf8");
        mysql_query('CREATE DATABASE `'.$project_en.'`');
        mysql_select_db($project_en,$conn);
        $sql = file_get_contents($sql_path.'/db_sql_tpl.sql');
        $sql = str_ireplace('{$project_cn}' , $project_cn , $sql);
        $sql = str_ireplace('{$project_en}' , $project_en , $sql);
        $split_sql = explode(";" , $sql);
        //print_r($split_sql);
        foreach($split_sql as $key=>$value){
            mysql_query($value);
        }
        mysql_close($conn);       
        
    }
    
    protected function copyFile($path , $project_en , $db_addr , $db_user , $db_pwd){
        $config_php = file_get_contents($path.'/config_init.php');
        $config_php = str_ireplace('{$project_en}',$project_en,$config_php);
        $config_php = str_ireplace('{$db_addr}',$db_addr,$config_php);
        $config_php = str_ireplace('{$db_user}',$db_user,$config_php);
        $config_php = str_ireplace('{$db_pwd}',$db_pwd,$config_php);
        //file_put_contents($path.'/config_test.php',$config_php);
        file_put_contents($path.'/config.php',$config_php);
        return $config_php;
    }
    
	protected function deleteFile($path){
		global $text;
		if (is_dir($path)){
			$handle=opendir($path);			
			while($list=readdir($handle)){
				if ($list=='.' || $list=='..'){
					//do nothing
				}else{
					$list=$path.'/'.$list;
				}
				switch ($list){
					case $list=='.' || $list=='..':
						//echo $list.' this is  special directory ';
						continue;
					case is_file($list):
						if (unlink($list)){
							$text=$text.'<span>delete file</span> '.$list.'';
						}else {
							$text=$text. 'delete file failure';
						}
						break;
					case is_dir($list):
						$text=$text. 'open directory '.$list.'';
						$this->deleteFile($list);
						break;
					default:
						//$text=$text.'default action '.$list.'';
						continue;
				}
			}
		}else{
			$text=$text. $path.' sorry the path is not directory';
		}
		return  $text;
	}
    
    /**
     * 备份现有数据库
     * */
    public function to_backup(){
        $this->display();
    } 
    
    /**
     * 数据库与文件的备份
     * 数据库不能使用“;”作分隔符
     * */
    public function backup(){
        $abs_dir=dirname(dirname(dirname(dirname(__FILE__))));
        $backup_sql = '';
        $backup_sql .= $this->backupConfig();
        $backup_sql .= $this->backupMenu();
        $backup_sql .= $this->backupUser();
        $backup_sql .= $this->backupContent();
        
        
        //echo $backup_sql;
        file_put_contents($abs_dir.'/Admin/Conf/db_sql_backup.sql',$backup_sql);
        $where['mate_key'] = C('PROJECT_NAME_EN');
        $config = M('Config')->where($where)->find();
        file_put_contents($abs_dir.'/Admin/Conf/project_en.txt',$config['mate_value']);
        $this->successAjax('数据备份成功!');
    }
    /**
     * dwz Ajax数据返回
     * success返回
     * */
    function successAjax($message ,$isCloseCurrent = false){
        $result  =  array();
        $result['statusCode']  =  1;	// ok:1
        $result['navTabId']  =  $_REQUEST['navTabId'];	// 刷新页面
        if($isCloseCurrent){
            $result['callbackType'] = 'closeCurrent';
        }else{
            $result['callbackType'] = '';
        }
        $result['message'] =  $message;
        echo json_encode($result);
        exit();
    }
    protected function backupConfig(){
        $backup_sql = '';
        $Config = M('Config');
        $backup_sql = " DROP TABLE IF EXISTS `config`#-#
                        CREATE TABLE `config` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `mate_key` varchar(100) DEFAULT NULL,
                          `mate_value` varchar(100) DEFAULT NULL,
                          PRIMARY KEY (`id`)
                        )DEFAULT CHARSET=utf8#-#";
        $backup_sql .= "insert  into `config`(`id`,`mate_key`,`mate_value`) values ";
        $list = $Config->select();
        $first = true;
        foreach($list as $key => $value){
            if($first){
                $backup_sql .= "(".$value['id'].",'".$value['mate_key']."','".$value['mate_value']."')";
                $first = false;
            }else{
                $backup_sql .= ",(".$value['id'].",'".$value['mate_key']."','".$value['mate_value']."')";
            }
        }
        return $backup_sql.'#-#';
    }
    
    protected function backupMenu(){
        $backup_sql = '';
        $Menu = M('Menu');
        $backup_sql = " DROP TABLE IF EXISTS `menu`#-#
                        CREATE TABLE `menu` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `name` varchar(100) DEFAULT NULL COMMENT '项目名称',
                          `level` int(11) DEFAULT '0' COMMENT '项目级别：0顶级，1为二级',
                          `pid` int(11) DEFAULT '0' COMMENT '非顶级目录>=0，属于某一目录id',
                          `manager` varchar(100) DEFAULT NULL COMMENT '负责人',
                          `remark` text COMMENT '备注',
                          `weight` int(11) DEFAULT '0' COMMENT '排序权值',
                          `custom_flag` int(11) DEFAULT '0' COMMENT '自定义页面标示，1表示自定义',
                          `custom_url` varchar(255) DEFAULT NULL COMMENT '自定义页面链接',
                          `index_display_flag` int(11) DEFAULT '0' COMMENT '首页展示:1yes,0no',
                          PRIMARY KEY (`id`)
                        )DEFAULT CHARSET=utf8#-#";
        $backup_sql .= "insert  into `menu`(`id`,`name`,`level`,`pid`,`manager`,`remark`,`weight`,`custom_flag`,`custom_url`,`index_display_flag`) values ";
        $list = $Menu->select();
        $first = true;
        foreach($list as $key => $value){
            if($first){
                $backup_sql .= "(".$value['id'].",'".$value['name']."',".$value['level'].","
                    .$value['pid'].",'".$value['manager']."','".$value['remark']."',"
                    .$value['weight'].",".$value['custom_flag'].",'".$value['custom_url']."',"
                    .$value['index_display_flag'].")";
                $first = false;
            }else{
                $backup_sql .= ",(".$value['id'].",'".$value['name']."',".$value['level'].","
                    .$value['pid'].",'".$value['manager']."','".$value['remark']."',"
                    .$value['weight'].",".$value['custom_flag'].",'".$value['custom_url']."',"
                    .$value['index_display_flag'].")";
            }
        }
        return $backup_sql.'#-#';
    }
    
    protected function backupUser(){
        $backup_sql = '';
        $User = M('User');
        $backup_sql = " DROP TABLE IF EXISTS `user`#-#
                        CREATE TABLE `user` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `account` varchar(100) NOT NULL COMMENT '账号',
                          `nickname` varchar(100) DEFAULT '办公人员' COMMENT '昵称',
                          `password` varchar(32) NOT NULL COMMENT 'md5',
                          `remark` varchar(255) DEFAULT NULL,
                          `status` int(11) NOT NULL DEFAULT '1' COMMENT '0禁用、1可用',
                          `access` int(11) NOT NULL DEFAULT '1' COMMENT '1=member  10=admin',
                          PRIMARY KEY (`id`)
                        )DEFAULT CHARSET=utf8#-#";
        $backup_sql .= "insert  into `user`(`id`,`account`,`nickname`,`password`,`remark`,`status`,`access`) values ";
        $list = $User->select();
        $first = true;
        foreach($list as $key => $value){
            if($first){
                
                $backup_sql .= "(".$value['id'].",'".$value['account']."','".$value['nickname']."','"
                    .$value['password']."','".$value['remark']."',".$value['status'].",".$value['access'].")";
                $first = false;
            }else{
                $backup_sql .= ",(".$value['id'].",'".$value['account']."','".$value['nickname']."','"
                    .$value['password']."','".$value['remark']."',".$value['status'].",".$value['access'].")";
            }
        }
        return $backup_sql.'#-#';
    }
    
    protected function backupContent(){
        $backup_sql = '';
        $Content = M('Content');
        $backup_sql = " DROP TABLE IF EXISTS `content`#-#
                        CREATE TABLE `content` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `menu_id` int(11) NOT NULL,
                          `title` varchar(100) DEFAULT NULL,
                          `author` varchar(100) DEFAULT NULL,
                          `update_time` int(11) DEFAULT NULL,
                          `remark` varchar(255) DEFAULT NULL,
                          `article` text,
                          PRIMARY KEY (`id`)
                        )DEFAULT CHARSET=utf8#-#";
        $backup_sql .= "insert into `content`(`id`,`menu_id`,`title`,`author`,`update_time`,`remark`,`article`) values ";
        $list = $Content->select();
        $first = true;
        foreach($list as $key => $value){
            if($first){
                
                $backup_sql .= "(".$value['id'].",".$value['menu_id'].",'".$value['title']."','"
                    .$value['author']."',".$value['update_time'].",'".$value['remark']."','".$value['article']."')";
                $first = false;
            }else{
                $backup_sql .= ",(".$value['id'].",".$value['menu_id'].",'".$value['title']."','"
                    .$value['author']."',".$value['update_time'].",'".$value['remark']."','".$value['article']."')";
            }
        }
        return $backup_sql.'#-#';
    }
    
    /**
     * 从备份文件中还原项目
     * */
    public function restore(){

        $db_addr = $_REQUEST['db_addr'];
        $db_user = $_REQUEST['db_user'];
        $db_pwd = $_REQUEST['db_pwd'];
        
        if(!isset($db_addr) || !isset($db_user) || 
            !isset($db_pwd)){
            echo '请补全未填写的必须字段。';
            exit(0);
        }
        $abs_dir=dirname(dirname(dirname(dirname(__FILE__))));
        $project_en = file_get_contents($abs_dir.'/Admin/Conf/project_en.txt');
        $this->restoreDB($abs_dir.'/Admin/Conf' , $project_en , $db_addr , $db_user , $db_pwd);
        $this->deleteFile($abs_dir.'/Admin/Runtime');
        echo '项目恢复成功，<a href="/'.$project_en.'">点击进入</a>。';
    }

    protected function restoreDB($sql_path , $project_en ,$db_addr , $db_user , $db_pwd){
        $conn = mysql_connect($db_addr,$db_user,$db_pwd);
        mysql_query("set names utf8");
        mysql_query('CREATE DATABASE `'.$project_en.'`');
        mysql_select_db($project_en,$conn);
        $sql = file_get_contents($sql_path.'/db_sql_backup.sql');
        $split_sql = explode("#-#" , $sql);
        //print_r($split_sql);
        foreach($split_sql as $key=>$value){
            mysql_query($value);
        }
        mysql_close($conn);       
        
    }
    
}
